import { request, RequestOptions, ClientRequest } from 'http';
import { createWriteStream } from 'fs';
import { URL } from 'url';

interface DownloadOptions {
    url: string,
    timeout?: number
}

const parseOpt: (opt: string | DownloadOptions) => RequestOptions = (opt) => {
    if (typeof opt === 'string') opt = {url: opt}
    let p = new URL(opt.url)
    
    return Object.assign(p, {path: p.pathname}, opt)
}

const download: (url: string | DownloadOptions, output?: string) => Promise<string> = (url, output = './output') => {

    return new Promise((resolve, reject) => 

        request(parseOpt(url), res => 

            res.on('error', reject)

            .on('end', () => resolve(output))

            .pipe(createWriteStream(output))
        )

        .on('error', reject)

        .end()
    )
}

export default download